package com.veinhorn.scrollgalleryview;

import com.github.chrisbanes.photoview.PhotoView;
import com.veinhorn.scrollgalleryview.loader.MediaLoader;
import com.veinhorn.scrollgalleryview.util.FactoryUtil;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.TableLayout;
import ohos.agp.utils.LayoutAlignment;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;

/**
 * ImageFragment
 *
 * @author veinhorn
 * @since 2021-03-24
 */
public class ImageFragment extends DirectionalLayout {
    private static final int TIMELONG = 300;

    /**
     * ImageFragment
     *
     * @param context
     * @param mediaInfo
     * @param isZoom
     */
    public ImageFragment(Context context, MediaInfo mediaInfo, boolean isZoom) {
        super(context);
        initViewData(context, mediaInfo, isZoom);
    }

    private void initViewData(Context context, MediaInfo mediaInfo, boolean isZoom) {
        Component rootView = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_image_fragment, this, true);
        rootView.setLayoutConfig(
                new DirectionalLayout.LayoutConfig(
                        LayoutConfig.MATCH_PARENT,
                        LayoutConfig.MATCH_PARENT));

        PhotoView photoView = (PhotoView) rootView.findComponentById(ResourceTable.Id_image_view);
        photoView.setWidth(FactoryUtil.getOptionalInfo(context).width);
        photoView.setHeight(FactoryUtil.getOptionalInfo(context).height);
        photoView.setZoomable(isZoom);
        if (mediaInfo != null) {
            Context mContext = getContext();
            TaskDispatcher taskDispatcher = mContext.getUITaskDispatcher();
            taskDispatcher.delayDispatch(new UiRunnable(mediaInfo, photoView),
                    TIMELONG);
        }
    }

    /**
     * UiRunnable
     *
     * @since 2021-03-24
     */
    final class UiRunnable implements Runnable {
        private MediaInfo mMediaInfo;
        private PhotoView mPhotoView;

        private UiRunnable(MediaInfo mediaInfo, PhotoView photoView) {
            this.mMediaInfo = mediaInfo;
            this.mPhotoView = photoView;
        }

        @Override
        public void run() {
            mMediaInfo.getLoader().loadMedia(getContext(), mPhotoView, new MediaLoader.SuccessCallback() {
                @Override
                public void onSuccess() {
                }
            });
        }
    }
}
